package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import database.DBManager;

public class Connection implements Runnable {

	private ServerSocket serverSocket;
	private Socket socket1;
	private Socket socket2;
	private InputStream socketIS1;
	private OutputStream socketOS2;
	private DBManager myDb;
	private Sender sender;
	
	public Connection(DBManager myDb){
		this.myDb = myDb;
		
		
	}
	
	public Sender getSender(){
		return sender;
	}
	
	private void searchData(){
		try {
			Thread thread = new Receiver(myDb, socketIS1, sender);
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void init(int port1, int port2) throws IOException, InterruptedException {
		/*
		serverSocket = new ServerSocket(port1);
		System.out.println("wait for input connection:");
		socket1 = serverSocket.accept();// wait until someone wants a connection
		socket1.setSoTimeout(5000);
		socketIS1 = socket1.getInputStream();

		serverSocket = new ServerSocket(port2);
		System.out.println("wait for output connection:");
		socket2 = serverSocket.accept();// wait until someone wants a connection
		socket2.setSoTimeout(5000);
		socketOS2 = socket2.getOutputStream();
		*/
		
		byte read;
		
		while(true)
		{
			try
			{
				serverSocket = new ServerSocket(port1);
				serverSocket.setSoTimeout(10000);

				//System.out.println("wait for connection:");
				socket1 = serverSocket.accept();//wait until someone wants a connection
				socket1.setSoTimeout(5000);
				socketIS1 = socket1.getInputStream();
		
				serverSocket = new ServerSocket(port2);
				serverSocket.setSoTimeout(10000);
				System.out.println("wait for connection2:");
				socket2 = serverSocket.accept();//wait until someone wants a connection
				socket2.setSoTimeout(5000);
				socketOS2 = socket2.getOutputStream();
				Thread.sleep(50);
				
				if(socketIS1.available() > 0)
				{
					read = (byte) socketIS1.read();
					if((char)read == 'S')
					{	
						socketOS2.write('O');
						socketOS2.flush();
						System.out.println("ok");
						break;
					}
				}
			}			
			catch(SocketTimeoutException e)
			{
//				System.out.println("Got an IOException: " + e.getMessage());
//				
//				
//				serverSocket.close();
			} 
			
			
//			System.out.println("restart");
			if( socket1 != null ){
				socket1.close();
			}
			if( socket2 != null ){
				socket2.close();
			}
			if( serverSocket != null )		
			{
				serverSocket.close();
				
			}
			
			Thread.sleep(50);
		}
		
		
	}

	public void run() {
		// TODO Auto-generated method stub
		try {
			init(6789, 5678);
			sender = new Sender(socketOS2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		searchData();
	}
	
}
